package com.realjinge.interceptor;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author realjinge
 *
 */
public class LoginFilter implements Filter {
	private static final String LOGIN_URL = "/weChat/index.do";

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request2 = (HttpServletRequest) request;
		HttpServletResponse response2 = (HttpServletResponse) response;
		String url = request2.getRequestURI();
		if (url != null && url.endsWith(".do")) {
			if (url.endsWith("/index.do") || url.endsWith("/login.do") || url.endsWith("/view.do")
					|| url.endsWith("/realjinge.do") || url.contains("admin")) {
				filterChain.doFilter(request2, response2);
				return;
			}
			String token = request2.getParameter("token");
			if (null == token || "".equals(token)) {
				token = (String) request2.getSession().getAttribute("token");
			}
			if (token != null && !"".equals(token)) {
				request2.getSession().setAttribute("token", token);
				filterChain.doFilter(request2, response2);
			} else {
				response2.sendRedirect(LOGIN_URL);
			}
		} else {
			filterChain.doFilter(request2, response2);
		}
	}

	/**
	 * 输出JSON字符串
	 * 
	 * @param response
	 * @param jsonMsg
	 */
	protected void out(HttpServletResponse response, String jsonMsg) {
		try {
			response.setContentType("text/json;charset=utf-8");
			response.getWriter().write(jsonMsg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
